package net.jcip.chapter5;

import java.util.List;
import java.util.Scanner;
import java.util.Vector;
import java.util.concurrent.Callable;

/**
 * UnsafeVectorHelpers
 * <p/>
 * Compound actions on a Vector that may produce confusing results
 *
 *  某些情况下, 需要添加锁来保证 同步容器的 复合操作;
 *
 *
 * @author Brian Goetz and Tim Peierls
 */
class UnsafeVectorHelpers {


    private static Object getLast(Vector list) {

        int lastIndex = list.size() - 1;
        return list.get(lastIndex);
    }

    private static void deleteLast(Vector list) {

        int lastIndex = list.size() - 1;
        list.remove(lastIndex);

    }


    /**
     * todo  验证
     * */
    public static void main(String[] args) throws InterruptedException {

        Vector<Integer> vector = new Vector<>(1000);

        for (int i = 0; i < 1000; i++) {
            vector.add(i) ;
        }

        Thread getThread = new Thread(() -> {

            for (int i = 0; i < 1000; i++) {
                UnsafeVectorHelpers.getLast(vector);
            }

        }, "get线程");


        Thread deleteThread = new Thread(() -> {

            for (int i = 0; i < 1000; i++) {

                UnsafeVectorHelpers.deleteLast(vector);
            }

        }, "delete线程");

        getThread.start();
        deleteThread.start();

        Scanner scanner = new Scanner(System.in);
        System.out.println("任意键退出.....");
        scanner.next();


    }


}
